﻿from flask import *
import time,sys,os
from dian_can_info_sql import *
import datetime,json

app = Flask(__name__)
app.config.from_object(__name__)

def response_return(code, msg, data):
    """[summary]
    Args:
        code ([type]): 200(请求成功),404(请求失败),500(服务器出错)
        msg ([type]): msg
        data ([type]): json_data
    Returns:
        [type]: [description]
    """
    if data == None:
        data = []
    return json.dumps({'code': code, 'msg': msg, 'data': list(data)}, ensure_ascii=False)

# 首页
@app.route('/dian_can_index')
def dian_can_index():
    data=user_slectTable()[::-1]
    all_data=[]
    zao_sum=0
    wu_sum=0
    wan_sum=0
    for i in data:
        temp={}
        temp['id']=i[0]
        temp['name']=i[1]
        temp['nian_ji']=i[2]
        temp['zao_number']=i[3]
        temp['wu_number']=i[4]
        temp['wan_number']=i[5]
        temp['eat_day']=i[6]
        temp['eat_week']=i[7]
        temp['dian_can_time']=i[8]
        zao_sum+=i[3]
        wu_sum+=i[4]
        wan_sum+=i[5]
        all_data.append(temp)
        
    return render_template('dian_can_index.html',all_data=all_data,zao_sum=zao_sum,wu_sum=wu_sum,wan_sum=wan_sum)

@app.route('/search_data',methods=['GET', 'POST'])
def search_data():
    name_key = request.form.get('name_key')
    nian_ji_key = request.form.get('nian_ji_key')
    month_key = request.form.get('month_key')
    data=user_slectTable()[::-1]
    all_data=[]
    zao_sum=0
    wu_sum=0
    wan_sum=0
    for i in data:
        temp={}
        if name_key in i[1] and nian_ji_key in i[2] and month_key in i[6]:
            temp['id']=i[0]
            temp['name']=i[1]
            temp['nian_ji']=i[2]
            temp['zao_number']=i[3]
            temp['wu_number']=i[4]
            temp['wan_number']=i[5]
            temp['eat_day']=i[6]
            temp['eat_week']=i[7]
            temp['dian_can_time']=i[8]
            zao_sum+=i[3]
            wu_sum+=i[4]
            wan_sum+=i[5]
            all_data.append(temp)
    return render_template('dian_can_index.html',all_data=all_data,zao_sum=zao_sum,wu_sum=wu_sum,wan_sum=wan_sum)

@app.route('/data_api',methods=['GET', 'POST'])
def data_api():
    try:
        data=user_slectTable()[::-1]
        all_data=[]
        for i in data:
            temp={}
            temp['id']=i[0]
            temp['name']=i[1]
            temp['nian_ji']=i[2]
            temp['zao_number']=i[3]
            temp['wu_number']=i[4]
            temp['wan_number']=i[5]
            temp['eat_day']=i[6]
            temp['eat_week']=i[7]
            temp['dian_can_time']=i[8]
            all_data.append(temp)
        return response_return('200', 'success', all_data)
    except:
        all_data=[]
        return response_return('404', 'fail', all_data)

@app.route('/input_data',methods=['GET', 'POST'])
def input_data():
    try:
        title="点餐信息上传成功！"
        time_stamp = datetime.datetime.now()
        time=str(time_stamp.strftime('%H:%M:%S')).split(':')[0]
        if int(time)>=23 or int(time) <=6:
            return render_template('up_data_ok.html',title="已超过点餐时间！")
        name = request.form.get('name')
        select_nian_ji = request.form.get('select_nian_ji')
        zao_numbers = request.form.get('zao_numbers')
        wu_numbers = request.form.get('wu_numbers')
        wan_numbers = request.form.get('wan_numbers')
        nian_ji_dict={"qi":"七年级","ba":"八年级","jiu":"九年级","shi":"高一","shi_yi":"高二","shi_er":"高三"}
        if name == '':
            title="姓名不能为空！"
            return render_template('up_data_ok.html',title=title)
        if zao_numbers == '' or int(zao_numbers) < 0:
            zao_numbers=0
        if wu_numbers == '' or int(wu_numbers) < 0 :
            wu_numbers=0
        if wan_numbers == '' or int(wan_numbers) < 0:
            wan_numbers=0
        # if int(zao_numbers)+int(wu_numbers)+int(wan_numbers)==0:
        #     title="您未点餐！"
        #     return render_template('up_data_ok.html',title=title)
        today = datetime.date.today()
        tomorrow = today + datetime.timedelta(days=1)
        week=tomorrow.isoweekday()
        weekday={1:"星期一",2:"星期二",3:"星期三",4:"星期四",5:"星期五",6:"星期六",7:"星期日"}
        today_week = today.isoweekday()
        time_stamp = datetime.datetime.now()
        time=str(time_stamp.strftime('%Y.%m.%d-%H:%M:%S'))+"-"+weekday[today_week]
        res=user_slect_name_day(str(name),tomorrow)
        if res != []:
            title="点餐信息已覆盖！"
            user_alter(res[0][0],int(zao_numbers),int(wu_numbers),int(wan_numbers),time)
            return render_template('up_data_ok.html',title=title)
        else:
            user_insertData(str(name),nian_ji_dict[select_nian_ji],int(zao_numbers),int(wu_numbers),int(wan_numbers),tomorrow,weekday[week],time)
            return render_template('up_data_ok.html',title=title)
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
        title="未知错误，请重新点餐！"
        return render_template('up_data_ok.html',title=title)

if __name__ == '__main__':
    app.run(debug=True)
